<template>
  <div class="yt-list-content">
    <div class="list-operation">
      <div id="worksEcharts" style="height: 400px;width: 100%;"></div>
      <div class="yt-btn yt-btn-ys" type="primary" @click="exportEchar"style="margin-bottom: 20px">{{$t('button.export')}}</div>
      <div class="yt-btn yt-btn" type="primary" style="margin-bottom: 20px;margin-left: 12px" @click="setUp">{{$t('button.sets')}}</div>
      <el-table :data="list" :empty-text="$t('placeholder.emptyText')" class="yt-table" style="width: 100%" v-loading="loading" :element-loading-text="$t('buPieChart.loading')" max-height="600">
        <!--<el-table-column type="index" align="center" :label="$t('buPieChart.buChart.index')" width="60"/>-->
        <el-table-column align="center" :label="$t('buPieChart.buChart.completedCost')" v-if="displayBlockNameStr['completedCost']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.completedCost}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.sumProjectHumanCost')" v-if="displayBlockNameStr['sumProjectHumanCost']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.sumProjectHumanCost}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.sumManageHumanCost')" v-if="displayBlockNameStr['sumManageHumanCost']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.sumManageHumanCost}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.managementCost')" v-if="displayBlockNameStr['managementCost']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.managementCost}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.businessExpenses')" v-if="displayBlockNameStr['businessExpenses']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.businessExpenses}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.amortization')" v-if="displayBlockNameStr['amortization']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.amortization}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.hqAmortization')" v-if="displayBlockNameStr['hqAmortization']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.hqAmortization}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('buPieChart.buChart.manageCostAmortization')" v-if="displayBlockNameStr['manageCostAmortization']">
          <template slot-scope="scope">
            <div v-format="'#,##0'">{{scope.row.manageCostAmortization}}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :title="$t('projectRevenue.dataReport.setVisible')" :visible.sync="TableTitleVisible">
        <yt-table-title :blockNameCode="blockNameCode" :displayBlockNameList ="displayBlockNameList" @cancel="cancel"></yt-table-title>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { queryBuCost, uploadEchar, exportBuCost } from '@/api/pmoReport/buPieChartReport';
  import { queryDisplayBlock } from '@/api/pmoReport/projectRevenue';
  import YtTableTitle from '@/components/yt-table-title/index';
  import echarts from 'echarts'
  export default {
    name: 'buPieChart',
    props: {
      // 查询次数
      query: {
        type: Number,
        default: 0
      },
      listQuery: {
        type: Object,
        default: {}
      }
    },
    components: { YtTableTitle },
    watch: {
      query: {
        handler() {
          this.getData()
        }
      }
    },
    data() {
      return {
        list: [],
        chart: null,
        loading: false,
        TableTitleVisible: false,
        blockNameCode: 'buPieChart',
        displayBlockNameList: [],
        displayBlockNameStr: {}
      };
    },
    mounted() {
      this.chart = echarts.init(document.getElementById('worksEcharts'))
      this.getData()
      this.getColumn();
    },
    methods: {
      cancel(val) {
        if (val) {
          this.getColumn();
        }
        this.TableTitleVisible = false
      },
      // 获取初始的栏位
      getColumn() {
        const data = {
          tableName: this.blockNameCode,
          userId: this.$store.getters.info.id
        }
        this.getMixinColumn(data)
      },
      getMixinColumn(data) {
        this.displayBlockNameStr = {}
        queryDisplayBlock(data).then(res => {
          if (res.status === 200) {
            this.displayBlockNameList = res.data
            for (const i in this.displayBlockNameList) {
              this.displayBlockNameStr[this.displayBlockNameList[i]] = true
            }
          }
        })
      },
      // 获取弹框的栏位
      setUp() {
        // 设置
        this.TableTitleVisible = true
      },
      exportEchar() {
        const base64Data = this.chart.getDataURL()
        // 生成图片
        uploadEchar({ base64Data }).then(res => {
          if (res.status === 200) {
            // 导出excel表格
            const imgPath = res.data
            const a = document.createElement('a');
            const href = exportBuCost(this.list, this.$store.getters.info.id, imgPath);
            a.download = Date.now();
            a.href = href;
            a.click();
          }
        })
      },
      getData() {
        this.loading = true
        if (this.chart) {
          this.chart.showLoading({
            text: this.$t('businessObjectives.loading'),
            color: '#409EFF',
            textColor: '#000',
            maskColor: 'rgba(255, 255, 255, 0.8)' // 背景色
          });
        }
        queryBuCost(this.listQuery).then(res => {
          if (res.data && res.data !== 'null' && res.data.length > 0) {
            this.list = res.data
            this.initChart(res.data[0])
          }
          if (this.chart) {
            this.chart.hideLoading();
          }
          this.loading = false
        })
      },
      initChart(list) {
        const data = [
          { name: this.$t('buPieChart.buChart.completedCost'), value: list.completedCost < 0 ? -1 * list.completedCost : list.completedCost }, // 完工成本（本年度）
          { name: this.$t('buPieChart.buChart.sumProjectHumanCost'), value: list.sumProjectHumanCost < 0 ? -1 * list.sumProjectHumanCost : list.sumProjectHumanCost }, // 专案人力成本
          { name: this.$t('buPieChart.buChart.sumManageHumanCost'), value: list.sumManageHumanCost < 0 ? -1 * list.sumManageHumanCost : list.sumManageHumanCost }, // 管理人力成本
          { name: this.$t('buPieChart.buChart.managementCost'), value: list.managementCost < 0 ? -1 * list.managementCost : list.managementCost }, // 管理成本
          { name: this.$t('buPieChart.buChart.businessExpenses'), value: list.businessExpenses < 0 ? -1 * list.businessExpenses : list.businessExpenses }, // 业务费用
          { name: this.$t('buPieChart.buChart.amortization'), value: list.amortization < 0 ? -1 * list.amortization : list.amortization }, // 折旧摊销
          { name: this.$t('buPieChart.buChart.hqAmortization'), value: list.hqAmortization < 0 ? -1 * list.hqAmortization : list.hqAmortization }, // HQ摊销
          { name: this.$t('buPieChart.buChart.manageCostAmortization'), value: list.manageCostAmortization < 0 ? -1 * list.manageCostAmortization : list.manageCostAmortization } // 管理成本摊销
        ]
        this.chart.setOption({
          tooltip: { trigger: 'item',
            // formatter: '{a} <br/>{b}b: {c} ({d}%)'
            formatter(data) {
              console.log(data)
              return data.seriesName + '<br/>' + data.name + ' : ' + String(data.value).replace(/\d{1,3}(?=(\d{3})+(\.|$))/g, '$&,') + '(' + data.percent.toFixed(2) + '%)';
            }
          },
          grid: { top: '3%', bottom: '3%', containLabel: true },
          // 图例的公用文本样式。
          legend: {
            textStyle: { fontSize: 14, color: '#606266' },
            left: '70%',
            align: 'auto',
            itemGap: 20,
            width: 200,
            data,
            formatter(name) {
              let value
              data.forEach(item => {
                if (name === item.name) {
                  value = item.value
                }
              })
              return name + ' : ' + String(value).replace(/\d{1,3}(?=(\d{3})+(\.|$))/g, '$&,')
            }
          },
          color: ['#5A9BD5', '#ed7d31', '#a2a7a1', '#ffbf01', '#4272ba', '#6aad44', '#255f91', '#a0470b'],
          series: [
            { name: this.$t('buPieChart.buChart.buChart'), type: 'pie', radius: ['70%', '90%'], avoidLabelOverlap: false,
              label: {
                normal: { position: 'center', show: true,
                  textStyle: { color: '#212121', fontSize: '18' },
                  formatter() { // 显示总数
                    let sun = 0
                    data.forEach(item => {
                      sun += item.value * 1
                    })
                    const total = String(sun).replace(/\d{1,3}(?=(\d{3})+(\.|$))/g, '$&,') // 格式化千分位
                    return total
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false,
                  formatter(p) {
                    return String(p.value).replace(/\d{1,3}(?=(\d{3})+(\.|$))/g, '$&,')
                  }
                }
              },
              data
            }
          ]
        })
      }
    }
  };
</script>
<style lang="scss" scoped>
  .title_select {
    float: right;
    padding-right: 20px;
  }

  /deep/ .yt-data-list .yt-list-title .title_select span {
    border-bottom: 0;
  }
</style>
